package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.entity.AddressBook;
import com.itheima.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
@Slf4j
public class AddressBookController {

    @Autowired
    private AddressBookService bookService;

    //新增地址
    @PostMapping
    public R<String> add(@RequestBody AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrenId());
        log.info("保存地址簿：{}", addressBook);
        bookService.save(addressBook);
        return R.success("保存成功");
    }

    //查询所有
    @GetMapping("/list")
    public R<List<AddressBook>> list(AddressBook addressBook) {
        //根据用户id
        addressBook.setUserId(BaseContext.getCurrenId());
        log.info("查询地址：{}", addressBook);
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(addressBook.getUserId() != null, AddressBook::getUserId, addressBook.getUserId());
        queryWrapper.orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> list = bookService.list(queryWrapper);
        return R.success(list);
    }

    @PutMapping("/default")
    public R<AddressBook> Default(@RequestBody AddressBook addressBook) {
        LambdaUpdateWrapper<AddressBook> queryWrapper = new LambdaUpdateWrapper<>();
        log.info("设置默认地址：{}", addressBook);
        queryWrapper.eq(AddressBook::getUserId, BaseContext.getCurrenId());
        queryWrapper.set(AddressBook::getIsDefault, 0);
        bookService.update(queryWrapper);

        addressBook.setIsDefault(1);
        bookService.updateById(addressBook);
        return R.success(addressBook);
    }

    //修改回显
    @GetMapping("/{id}")
    public R<AddressBook> get(@PathVariable Long id) {
        //获取id
        AddressBook byId = bookService.getById(id);
        if (byId != null) {
            return R.success(byId);
        } else {
            return R.error("没有此数据");
        }
    }
    @GetMapping("/default")
    public R<AddressBook> getdefault(){
LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(AddressBook::getUserId,BaseContext.getCurrenId());
queryWrapper.eq(AddressBook::getIsDefault,1);
        AddressBook list = bookService.getOne(queryWrapper);
        if (list==null){
            return R.error("没找到该地址");
        }
        else {
            return R.success(list);
        }
    }


    //TODO/保存修改
    @PutMapping
    public R<String> put(AddressBook addressBook){
return null;
    }
}
